﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MailService.Application.Contract;
using Microsoft.Extensions.Logging;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Emailing;
using Volo.Abp.TextTemplating;

namespace MailService.Application.AppService
{
    public class MailManager : IMailManager, ITransientDependency
    {
        private readonly ILogger<MailManager> _logger;
        private readonly ITemplateRenderer _templateRenderer;
        private readonly IEmailSender _emailSender;

        public MailManager(
            ITemplateRenderer templateRenderer,
            IEmailSender emailSender,
            ILogger<MailManager> logger)
        {
            _templateRenderer = templateRenderer;
            _emailSender = emailSender;
            _logger = logger;
        }
        
        /// <summary>
        /// 发送邮件模板
        /// </summary>
        /// <param name="template">枚举自MailResourceTemplateDefinitionProvider</param>
        /// <param name="receiver">邮件接收方</param>
        /// <param name="subject">枚举自MailSubject</param>
        /// <param name="model">方法返回模板需要渲染的数据对象</param>
        /// <param name="globalData">方法返回邮件模板使用的全局数据对象</param>
        public async Task<Exception> SendMailWithTemplateAsync(string template, string receiver, string subject, Func<object> model, Func<Dictionary<string, object>> globalData = null)
        {
            try
            {
                await _emailSender.SendAsync(
                    receiver,
                    subject,
                    await _templateRenderer.RenderAsync(
                        template,
                        model: model?.Invoke(),
                        globalContext: globalData?.Invoke()));
            }
            catch (Exception e)
            {
                _logger.LogException(e);
                return e;
            }

            return null;
        }
    }
}